package com.example.lotterysystem.common.interceptor;

import com.example.lotterysystem.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final static Logger logger= LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token=request.getHeader("user_token");
        logger.info("获取token：{}",token);
        logger.info("获取请求路径：{}",request.getRequestURI());
        //2.解析token
        Claims claims=JWTUtil.parseJWT(token);
        if (claims == null){
            logger.error("JWT令牌解析失败！");
            //设置response的状态码
            response.setStatus(401);
            return false;
        }
        logger.info("JWT令牌解析成功！放行");
        return true;
    }
}
